﻿using System;
using Missbot.Service;
using MongoDB.Bson.Serialization.Attributes;

namespace Missbot.Core.Cache
{
    /// <summary>
    /// 用户信息缓存记录
    /// </summary>
    public class PersonCacheRecord : DbBaseEntity
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserID { get; init; }

        /// <summary>
        /// 键
        /// </summary>
        public string Key { get; init; }

        /// <summary>
        /// 值
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? ExpiryTime { get; set; }
    }

    public static class PersonCacheRecordDA
    {
        /// <summary>
        /// 根据用户ID和键获取缓存记录
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Key">键</param>
        /// <returns>缓存记录</returns>
        public static PersonCacheRecord Get(string UserID, string Key)
        {
            var record = MongoService<PersonCacheRecord>.GetOnly(p => p.UserID == UserID && p.Key == Key);
            if (record != null)
            {
                return record;
            }

            record = new PersonCacheRecord {UserID = UserID, Key = Key};
            MongoService<PersonCacheRecord>.Insert(record);

            return record;
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        public static void Update(this PersonCacheRecord entity)
        {
            MongoService<PersonCacheRecord>.Update(entity);
        }
    }
}